package initialize

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"goods_srv/global"
)

func InitConsul() {
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", global.ServerConfig.ConsulConfig.ConsulHost, global.ServerConfig.ConsulConfig.ConsulPort)
	client, err := api.NewClient(config)
	if err != nil {
		zap.S().Panic(err)
	}
	check := &api.AgentServiceCheck{
		Interval:                       "2s",
		Timeout:                        "5s",
		GRPC:                           fmt.Sprintf("%s:%d", global.ServerConfig.IP, global.ServerConfig.Port),
		DeregisterCriticalServiceAfter: "1s",
	}
	registration := new(api.AgentServiceRegistration)
	registration.Name = global.ServerConfig.ServerName
	registration.ID = global.ServerID
	registration.Address = global.ServerConfig.IP
	registration.Port = global.ServerConfig.Port
	registration.Tags = global.ServerConfig.ConsulConfig.Tags
	registration.Check = check
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		zap.S().Panic(err)
	}
}
